<?php

namespace Frieza\Modules\IdeaBook\Controllers;

use Doraemon\cache\Queue;
use Doraemon\model\Article;
use Doraemon\model\Blank;
use Doraemon\model\IdeaBookNotify;
use Doraemon\model\IdeaBookNotifyItem;
use Doraemon\service\Share;
use Doraemon\tools\IdGen;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Encore\Admin\Grid;
use Doraemon\model\Member;
use Doraemon\model\Photos;
use Doraemon\tools\ImgUrl;
use Doraemon\cache\UserNick;
use Doraemon\model\IdeaBook;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\model\AdmUserType;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Doraemon\model\AdmIdeaBookMark;
use Doraemon\model\Ideabookcollect;
use Doraemon\service\es\EsIdeabook;
use App\Http\Controllers\Controller;
use Doraemon\tools\HhzNiceLivingUrl;
use Encore\Admin\Grid\Displayers\Actions;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\service\IdeaBook\IdeaBookMarkService;

class IdeaBookController extends Controller
{
    //选项级联
    const LIST_USER = 1;
    const LIST_TYPE = 2;
    const LIST_OPTION = [
        self::LIST_USER => "所有用户",
        self::LIST_TYPE => "认证标签"
    ];

    public function index(Request $request, Content $content)
    {

        $page = $request->input("page", 1);
        $pageSize = $request->input("per_page", 20);
        $requestData = $request->all();
        $where = [];
        $start = ($page - 1) * $pageSize;

        $showPic = $requestData["show_pic"];
        $photoNum = $requestData["photo_num"];
        $editTime = $requestData["edit_time"];

        $where["page"] = intval($start / $pageSize) + 1;
        $where["page_size"] = $pageSize;
        $where["sort"] = "id";
        $where["fl"] = "id,uid";

        //起始时间-结束时间
        if (!empty($editTime["start"]) && !empty($editTime["end"])) {
            $where["start_time"] = strtotime($editTime["start"]);
            $where["end_time"] = strtotime($editTime["end"]);
        }
        //最少图片-最多图片
        if ($photoNum["start"] < $photoNum["end"]) {
            $where["min_num"] = (int)$photoNum["start"];
            $where["max_num"] = (int)$photoNum["end"];
        }
        //标题
        if (!empty($requestData["title"])) {
            $where['title'] = trim($requestData["title"]);
        }
        //昵称
        if (!empty($requestData["nick"])) {
            $uid = UserNick::nick2uid($requestData["nick"]);
            if ($uid) {
                $uids = [$uid];
            } else {
                $uids = Member::select(["uid"], ["nick[~]" => $requestData["nick"]]);
                $uids = array_map(function ($v) {
                    return $v['uid'];
                }, $uids);
            }
            $uid = implode(',', $uids);
            $where['uid'] = $uid;
        }
        //图片id
        if (!empty($requestData["photo_id"])) {
            $photoIds = [];
            for ($i = 0; $i < 4; $i++) {
                $res = Ideabookcollect::getIdeabooksByPhotoid($i, $requestData["photo_id"]);
                if ($res) {
                    array_push($photoIds, $res[0]["idea_book_id"]);
                }
            }
            $photosId = implode(',', $photoIds);
            $where["id"] = $photosId;
        }
        //备注
        if (!empty($requestData["remark"])) {
            $ideaBookIds = AdmIdeaBookMark::getDataByWhere("idea_book_id", ["remark[~]" => $requestData["remark"]]);
            $where['id'] = $ideaBookIds;
        }
        if (!empty($requestData['uid'])) {
            $where['uid'] = $requestData['uid'];
        }
        //用户和标签
        $listkey = 0;
        if (!empty($requestData["key"])) {
            $listkey = $requestData["key"];
        }

        if (!empty($requestData["key"]) && $requestData["id"] != "") {
            //用户
            if ($requestData["key"] == "1") {
                $whereType["LIMIT"] = [0, 1000];
                $whereType["ORDER"] = ["uid" => "DESC"];
                $whereType["type"] = $requestData["id"];

                $uids = Member::getUserInfoByWhere("uid", $whereType);

            }
            //标签
            if ($requestData["key"] == "2") {
                $uids = AdmUserType::getUidsByAuthTag($requestData["id"], 1, 1000);
            }


            //dump($uids);
            $whereUid["uid"] = $uids;
            $resUids = IdeaBook::getInfosByWhere("uid", $whereUid);
            //dump($res);
            $uid = implode(',', $resUids);
            $where['uid'] = $uid;
        }
        //dump($requestData);
        //dump($where);
        $infos = EsIdeabook::searchAll($where);
        //dump($infos);

        $rows = [];
        //dump($infos["rows"]);
        foreach ($infos["rows"] as $key => $value) {
            $ideaBookInfos = IdeaBook::getIdeaBookById($value["id"]);
            $userInfos = Member::getOne($value['uid']);
            $ideaBookInfos["nick"] = $userInfos["nick"];
            $ideaBookMark = AdmIdeaBookMark::getDataByWhere("remark", [
                "idea_book_id" => $value["id"],
                "uid" => $value["uid"],
            ]);
            $ideaBookInfos["remark"] = $ideaBookMark[0];
            //dump($ideaBookInfos['id']);
            $params = [
                'link' => HhzNiceLivingUrl::getIdeaBookLink($ideaBookInfos['id']),
                'type' => 'link',
            ];
            $ideaBookInfos["qr_code"] = ImgUrl::getQrcode(json_encode($params));

            //获取图片地址
            $picId = Ideabookcollect::getPhotos($value['uid'], $value['id']);
            $cover_img = explode(",", $ideaBookInfos['cover_img']);
            $photo_arr = array_unique(array_merge($cover_img, $picId));
            //dump($photo_arr);
            $picUrlArr = [];
            if ($showPic) {
                foreach ($photo_arr as $id) {
                    if ($id == "") {
                        continue;
                    }
                    $picData = Photos::getPhoto($id);
                    $picUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picData['pic_id'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
                    array_push($picUrlArr, $picUrl);
                }
            }
            $ideaBookInfos['pic_num'] = count($picUrlArr);
            $ideaBookInfos['pic_arr'] = $picUrlArr;

            array_push($rows, $ideaBookInfos);
        }

        $gridModel = new pGridDataModel($rows, $infos["total"], ['perPage' => $pageSize]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($listkey) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->expandFilter();

            $grid->filter(function (\Encore\Admin\Grid\Filter $filter) use ($listkey) {

                $filter->disableIdFilter();

                $filter->column(1 / 2, function ($filter) {
                    $filter->between("edit_time", "时间段")->datetime();
                    !
                    $filter->between("photo_num", "图片数量");
                    $filter->dropDown("Find", [
                        "title" => "收藏夹名称",
                        "nick" => "用户昵称",
                        "uid" => "用户ID",
                        "photo_id" => "图片ID",
                        "remark" => "备注"
                    ]);
                });

                $filter->column(1 / 2, function ($filter) use ($listkey) {

                    $tempList = $this->optionList($listkey);
                    foreach ($tempList as $key => $value) {
                        $optionList[$value["id"]] = $value["text"];
                    }

                    $filter->equal('key', '标签or用户')->select(self::LIST_OPTION)->load('id', "getoption");
                    $filter->equal('id', '具体选项')->select($optionList);

                    $filter->in("show_pic", " 展示图片")->checkbox([
                        '1' => ''
                    ]);
                });

                $filter->expend();
            });

            $grid->column("name", "收藏夹名称")->width(100);

            $grid->column("id", "收藏夹id");

            $grid->column("nick", "创建者")->display(function () {
                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >" . $this->nick . "</a>";
            })->width(100);

            $grid->column("create_time", "创建时间")->display(function () {
                return date("Y-m-d H:i:s", $this->create_time);
            });

            $grid->column("description", "描述");

            $grid->column("remark", "备注")->editable('textarea');

            $grid->column("qr_code", '二维码')->image('', 180, 180);

            $grid->column("pic_num", "图片数")->default(0);

            $grid->column("pic_arr", "新图片")->carousel($width = 150, $height = 150);

            $grid->actions(function (Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();

                if ($actions->row->status) {
                    $actions->prepend('<a class="fa reload-data received-package" data-id="' . $actions->row->id . '" data-opt ="delete" href="javascript:;" " >删除</a>');
                } else {
                    $actions->prepend('<a class="fa reload-data received-package" data-id="' . $actions->row->id . '" data-opt ="recovery" href="javascript:;" " >恢复</a>');
                }

                $res = IdeaBookMarkService::eliteStatus($actions->row->id);
                if ($res) {
                    $actions->prepend('<a class="fa reload-data received-package" data-id="' . $actions->row->id . '" data-opt ="remove" href="javascript:;" " >取消精华</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                } else {
                    $actions->prepend('<a class="fa reload-data received-package" data-id="' . $actions->row->id . '" data-opt ="add" href="javascript:;" >设置精华</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                }

                $res = IdeaBookNotify::select('*', [
                    'idea_book_id' => $actions->row->id,
                ]);
                if ($res) {
                    $actions->prepend('<a class="fa reload-data" >已发通知</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                } else {
                    $actions->prepend('<a class="fa reload-data received-package" data-id="' . $actions->row->id . '" data-opt ="sendNotify" href="javascript:;" >下发通知</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                }
            });

            Admin::script($this->optionSubmit());

        });

        $tab = new Tab();
        $tab->add("收藏夹", $listGrid->render());
        $content->row($tab);
        return $content->header("收藏夹搜索")->breadcrumb(["text" => "收藏夹搜索"]);

    }

    //通过key获取id
    public function getOption(Request $request)
    {
        $listkey = $request->get('q');
        $res = $this->optionList($listkey);
        return response()->json($res);
    }

    //级联
    public function optionList($listkey)
    {
        $res = [];
        if ($listkey == self::LIST_USER) {
            $res = [
                "0" => [
                    "id" => Member::USER_COMMON,
                    "text" => "普通用户"
                ],
                "1" => [
                    "id" => Member::AUTH_USER_BRAND,
                    "text" => "品牌"
                ],
                "2" => [
                    "id" => Member::AUTH_USER_DESIGNER,
                    "text" => "设计师"
                ],
                "3" => [
                    "id" => Member::AUTH_USER_V,
                    "text" => "媒体"
                ]
            ];
        } else {
            if ($listkey == self::LIST_TYPE) {
                $res = [
                    "0" => [
                        "id" => AdmUserType::AUTH_TAG_NO_AUTH,
                        "text" => "暂不认证"
                    ],
                    "1" => [
                        "id" => AdmUserType::AUTH_TAG_TEST_ACCOUNT,
                        "text" => "测试账号"
                    ],
                    "2" => [
                        "id" => AdmUserType::AUTH_TAG_SUSPECTED_BUSINESS,
                        "text" => "疑似商业用户"
                    ],
                    "3" => [
                        "id" => AdmUserType::AUTH_TAG_WAIT_DESIGNER,
                        "text" => "待认证设计师"
                    ],
                    "4" => [
                        "id" => AdmUserType::AUTH_TAG_WAIT_BRAND,
                        "text" => "待认证品牌"
                    ],
                    "5" => [
                        "id" => AdmUserType::AUTH_TAG_WAIT_MEDIA,
                        "text" => "待认证媒体"
                    ],
                    "6" => [
                        "id" => AdmUserType::AUTH_TAG_EXAMPLE_ALTER,
                        "text" => "居住榜样备选"
                    ]
                ];
            }
        }

        return $res;
    }

    //添加备注
    public function remark(Request $request)
    {
        $requestData = $request->all();

        $ideaBookId = $requestData['pk'];
        $ideaBookData = IdeaBook::getIdeaBookById($ideaBookId);

        $data['admin_id'] = Admin::user()->id;
        $data['idea_book_id'] = $ideaBookId;
        $data['remark'] = $requestData['value'];
        $data['addtime'] = time();
        $data['uid'] = $ideaBookData["uid"];

        $res = IdeaBookMarkService::modifyRemark($data);

        $msg = $this->sendMsg($res);

        return $msg;
    }

    //更改精华状态
    public function editElite(Request $request)
    {
        $requestData = $request->all();
        $ideaBookId = $requestData['id'];
        $opt = $requestData['opt'];

        $ideaBookData = IdeaBook::getIdeaBookById($ideaBookId);

        $data['admin_id'] = Admin::user()->id;
        $data['idea_book_id'] = $ideaBookId;
        $data['addtime'] = time();
        $data['uid'] = $ideaBookData["uid"];

        if ($opt == "add") {
            $data['if_elite'] = 1;
        } else {
            $data['if_elite'] = 0;
        }

        $res = IdeaBookMarkService::modifyElite($data);

        $msg = $this->sendMsg($res);

        return $msg;
    }

    //更改灵感集状态
    public function editIdeaBook(Request $request)
    {

        $requestData = $request->all();
        $ideaBookId = $requestData['id'];
        $opt = $requestData['opt'];

        $IdeaBookData = IdeaBook::getIdeaBookById($ideaBookId);

        if ($opt == "delete") {
            $data['status'] = IdeaBook::STATUS_DEL;
        } else {
            $data['status'] = IdeaBook::STATUS_NORMAL;
        }
        $data['uid'] = $IdeaBookData['uid'];
        $id = $IdeaBookData['id'];

        $res = IdeaBook::updateIdeaBookById($id, $data);

        $msg = $this->sendMsg($res);

        return $msg;

    }

    //预定义错误信息
    public function sendMsg($res)
    {
        if ($res) {
            $msg = [
                "code" => 1,
                "message" => "执行成功"
            ];
        } else {
            $msg = [
                "code" => 0,
                "message" => "执行失败"
            ];
        }

        return $msg;
    }

    //所选操作提交
    public function optionSubmit()
    {
        return <<<SCRIPT
           
            $('.received-package').unbind('click').click(function() {
            var id = $(this).data('id');
            var opt = $(this).data('opt');
            swal({
                title: "是否确认?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {                  
                    switch(opt) {
                        case "add":
                            $.post('editElite', {'id':id,'opt':opt}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.message, '', 'success');
                             } else {
                                swal(data.message, '', 'error');
                             }                                                                                                                                    
                            });
                            break;
                        case "remove":
                            $.post('editElite', {'id':id,'opt':opt}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.message, '', 'success');
                             } else {
                                swal(data.message, '', 'error');
                             }                                                                                                                                    
                            });
                            break;
                        case "delete":
                            $.post('editIdeaBook', {'id':id,'opt':opt}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.message, '', 'success');
                             } else {
                                swal(data.message, '', 'error');
                             }                                                                                                                                    
                            });
                            break;
                        case "recovery":
                            $.post('editIdeaBook', {'id':id,'opt':opt}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.message, '', 'success');
                             } else {
                                swal(data.message, '', 'error');
                             }                                                                                                                                    
                            });
                            break;
                        case "sendNotify":
                            $.post('notifyIdeaBook', {'id':id,'opt':opt}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.message, '', 'success');
                             } else {
                                swal(data.message, '', 'error');
                             }                                                                                                                                    
                            });
                            break;
                    }                 
                }
            });
        });
        SCRIPT;
    }

    public function notifyIdeaBook(Request $request)
    {
        $requestData = $request->all();
        $ideaBookId = $requestData['id'];
        $opt = $requestData['opt'];

        $aIdeaBook = \Doraemon\service\Ideabook::getIdeaBookById($ideaBookId);

        $iTimestamp = time();

        $aObj = Ideabookcollect::select("*", [
            "uid" => $aIdeaBook['uid'],
            "idea_book_id" => $ideaBookId,
            "status" => [
                IdeaBook::STATUS_NORMAL,
            ]
        ]);
        foreach ($aObj as $row) {
            $sObjId = $row['photo_id'];
            $iType = IdParse::getType($sObjId);
            $iToUid = 0;

            $oExist = IdeaBookNotifyItem::select("*", [
                'obj_id' => $sObjId,
                'obj_type' => $iType,
            ]);
            if ($oExist) {
                continue;
            }

            $shareInfo = Share::getShare($sObjId, $iType);
            Log::debug('shareInfo', $shareInfo);
            $sLink = '';
            $cover_img = $shareInfo['wechat']['cover_img'];
            $desc = '暂无文字内容';
            switch ($iType) {
                case IdGen::TYPE_PHOTO:
                    $sLink = HhzNiceLivingUrl::getNoteDetailLink($sObjId);

                    $note = Photos::get("*", ['id' => $sObjId]);
                    Log::debug("通知note", [$note]);
                    if ($note) {
                        if ($note['title']) {
                            $desc = mb_substr($note['title'], 0, 10);
                            if (mb_strlen($note['title']) > 10) {
                                $desc = $desc . '...';
                            }
                        }elseif ($note['remark']) {
                            $desc = mb_substr($note['remark'], 0, 10);
                            if (mb_strlen($note['remark']) > 10) {
                                $desc = $desc . '...';
                            }
                        }
                        $iToUid = $note['uid'];
                    }
                    break;
                case IdGen::TYPE_ARTICLE:
                    $sLink = HhzNiceLivingUrl::getArticleDetailLink($sObjId);

                    $article = Article::get("*", ['aid' => $sObjId]);
                    if ($article) {
                        if ($article['title']) {
                            $desc = mb_substr($article['title'], 0, 10);
                            if (mb_strlen($article['title']) > 10) {
                                $desc = $desc . '...';
                            }
                        }elseif ($article['description']) {
                            $desc = mb_substr($article['description'], 0, 10);
                            if (mb_strlen($article['description']) > 10) {
                                $desc = $desc . '...';
                            }
                        }
                        $iToUid = $article['uid'];
                    }
                    break;
                case IdGen::TYPE_BLANK:
                    $sLink = HhzNiceLivingUrl::getBlankDetailLink($sObjId);
                    $blank = Blank::get("*", ['bid' => $sObjId]);
                    if ($blank) {
                        $iToUid = $blank['uid'];
                    }
                    break;
            }

            if (empty($iToUid)) {
                Log::error('目标用户为空', [$row]);
                continue;
                $msg = $this->sendMsg(false);
                return $msg;
            }

            //通知用户
            $params = [
                'to_uids' => [$iToUid],
                'msgInfo' => [
                    'send_user' => '6084737',
                    'con_type' => \Doraemon\model\AdmMsgSendDetails::CON_TYPE_RICH_TEXT,//11=富文本
                    'content' => [
                        [
                            'con_type' => \Doraemon\model\AdmMsgSendDetails::CON_TYPE_IMG_TXT,//2=图文
                            'content' => json_encode([
                                'title' => '本条内容被选中',
                                'desc' => $desc,
                                'cover_img' => $cover_img,
                                'link' => $sLink,
                            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                        ],
                        [
                            'con_type' => \Doraemon\model\AdmMsgSendDetails::CON_TYPE_TEXT,
                            'content' => json_encode([
                                'con' => '感谢住友！',
                            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                        ],
                        [
                            'con_type' => \Doraemon\model\AdmMsgSendDetails::CON_TYPE_TEXT,
                            'content' => json_encode([
                                'con' => '你的内容提供了很棒的居住灵感，已被好好住编辑部选用，我们将通过好好住官方新媒体账号发布，帮助到更多的人。',
                            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                        ],
                        [
                            'con_type' => \Doraemon\model\AdmMsgSendDetails::CON_TYPE_TEXT,
                            'content' => json_encode([
                                'con' => '如有疑问，请私信@好好住编辑部。',
                            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                        ],
                    ],
                ]
            ];
            Log::debug("下发私信通知", $params);
            Queue::insertQueue('queue/im/send', $params, Queue::QUEUE_DORAEMON);

            IdeaBookNotifyItem::insert([
                'obj_id' => $sObjId,
                'obj_type' => $iType,
                'addtime' => $iTimestamp,
            ]);
        }

        IdeaBookNotify::insert([
            "idea_book_id" => $ideaBookId,
            'addtime' => $iTimestamp,
        ]);

        $msg = $this->sendMsg(true);
        return $msg;
    }
}